#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "settings.h"

int main(int argc, char *argv[]) {
	printf("Server start\n");

	int fd_listener = socket(AF_INET, SOCK_STREAM, 0);
	if (fd_listener < 0) {
		perror("socket");
		return (1);
	}

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if (bind(fd_listener, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
		perror("bind");
		return (1);
	}

	listen(fd_listener, 1);

	while (1) {
		int fd_client = accept(fd_listener, NULL, NULL);
		if (fd_client < 0) {
			perror("accept");
			continue;
		}
		while (1) {
			char buffer[BUFFER_SIZE];
			int read = recv(fd_client, buffer, BUFFER_SIZE, 0);
			if (read <= 0) {
				break;
			}
			send(fd_client, buffer, read, 0);
		}
		close(fd_client);
	}

	return(0);
}
